package cn.mw.cmdb.util;

import cn.hutool.core.bean.BeanDesc;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.PropDesc;
import cn.mw.components.mongodb.anno.CMDBProperty;
import cn.mw.components.mongodb.mapper.AggregateQueryFilter;
import cn.mw.components.mongodb.mapper.DefaultMethodMapper;
import cn.mw.components.mongodb.mapper.QueryFilter;
import org.springframework.data.mongodb.core.aggregation.AggregationOperation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import java.lang.reflect.Field;
import java.util.Iterator;
import java.util.List;

public class LogicDelQueryFilter implements QueryFilter, AggregateQueryFilter {
    private Class clazz;

    public LogicDelQueryFilter(Class clazz){
        this.clazz = clazz;
    }

    @Override
    public void filter(Query query, List<Criteria> criteriaList, DefaultMethodMapper mapper) {
        BeanDesc desc = BeanUtil.getBeanDesc(clazz);
        Iterator<PropDesc> ite = desc.getProps().iterator();
        while (ite.hasNext()) {
            PropDesc propDesc = ite.next();
            Field field = propDesc.getField();
            CMDBProperty annotation = field.getAnnotation(CMDBProperty.class);
            if(null == annotation){
                continue;
            }
            if(annotation.logicDel()){
                Criteria criteria = Criteria.where(field.getName()).is(false);
                criteriaList.add(criteria);
            }
        }
    }

    @Override
    public void aggregateFilter(Class targetClass ,List<AggregationOperation> aggregationOperationList ,List<Criteria> criteriaList ,DefaultMethodMapper mapper) throws Exception {
        filter(null ,criteriaList ,null);
    }
}
